package leetcode.code2569;

import java.util.ArrayList;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	int[] cnt1;
	int[] nums1;
	boolean[] update;

	public long[] handleQuery(int[] nums1, int[] nums2, int[][] queries) {
		List<Long> list = new ArrayList<>();
		long sum = 0;
		for (int num : nums2) {
			sum += num;
		}
		int n = nums1.length;
		cnt1 = new int[n << 2];
		update = new boolean[n << 2];
		this.nums1 = nums1;
		this.build(1, 1, n);
		for (int[] query : queries) {
			int a = query[0], b = query[1], c = query[2];
			if (a == 1) {
				update(1, 1, n, b + 1, c + 1);
			} else if (a == 2) {
				sum += 1l * cnt1[1] * b;// Long
			} else {
				list.add(sum);
			}
		}
		long[] ans = new long[list.size()];
		for (int i = 0; i < list.size(); i++) {
			ans[i] = list.get(i);
		}
		return ans;
	}

	private void build(int o, int l, int r) {
		if (l == r) {
			cnt1[o] = this.nums1[l - 1];
		} else {
			int m = ((r - l) >> 1) + l;
			build(o << 1, l, m);
			build(o << 1 | 1, m + 1, r);
			cnt1[o] = cnt1[o << 1] + cnt1[o << 1 | 1];
		}
	}

	private void reverse(int o, int l, int r) {
		cnt1[o] = r - l + 1 - cnt1[o];
		update[o] = !update[o];
	}

	private void update(int o, int l, int r, int L, int R) {
		if (L <= l && r <= R) {
			this.reverse(o, l, r);
		} else {
			int m = ((r - l) >> 1) + l;
			if (update[o]) {
				this.reverse(o << 1, l, m);
				this.reverse(o << 1 | 1, m + 1, r);
				this.update[o] = false;
			}
			if (L <= m)
				update(o << 1, l, m, L, R);
			if (m < R)
				update(o << 1 | 1, m + 1, r, L, R);
			cnt1[o] = cnt1[o << 1] + cnt1[o << 1 | 1];
		}
	}

	@Override
	public void debug4() {
		H.print(this.handleQuery(H.str2array3("[1,0,1]"), H.str2array3("[0,0,0]"),
				H.str2array1("[[1,1,1],[2,1,0],[3,0,0]]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
